﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Dal.NSDalMusic;
using Ninject.Core;
using Hotnet.Entity;
using Hotnet.Entity.Search;

namespace Hotnet.Biz.NSBizMusic
{
	public class BizMusic : BaseBiz<Music>
	{
		private static DalMusic db = new DalMusic();

		private BizLyric _BizLyric;
		private BizLyric BizLyric
		{
			get
			{
				if (_BizLyric == null)
					_BizLyric = new BizLyric();
				return _BizLyric;
			}
		}

		private BizMusicXTag _BizMusicXTag;
		private BizMusicXTag BizMusicXTag
		{
			get
			{
				if (_BizMusicXTag == null)
					_BizMusicXTag = new BizMusicXTag();
				return _BizMusicXTag;
			}
		}


		public BizMusic() : base(db) { }

		public Music[] ListMusicByCategoryID(int categoryId, int pageNo, int pageSize, out int totalSize, SearchMusicCondition smc)
		{
			var musicList = db.ListMusicByCategoryID(categoryId, pageNo, pageSize, out totalSize, smc);
			return musicList;
		}

		public Music[] ListMusicByGroupID(int groupId, SearchMusicCondition smc)
		{
			var musicList = db.ListMusicByGroupID(groupId, smc);
			return musicList;
		}

		public override void Insert(Music music)
		{
			music.AddTime = DateTime.Now;
			db.Insert(music);
			BizMusicXTag.SaveTags(music.Tags, music.MusicID);
			BizLyric.Insert(new Lyric
			{
				MusicID = music.MusicID,
				LyricWords = music.LyricWords
			});

		}
		public override void Delete(int musicId)
		{
			BizLyric.Delete(musicId);
			BizMusicXTag.DeleteAllByMusicID(musicId);
			base.Delete(musicId);
		}

		public Music GetAll(int id)
		{
			var music = db.Get(id);
			music.Tags = BizMusicXTag.GetTagStringsByMusicID(id);
			music.LyricWords = BizLyric.Get(music.MusicID).LyricWords;
			return music;
		}

		public void UpdateAll(Music music)
		{
			BizMusicXTag.DeleteAllByMusicID(music.MusicID);
			BizMusicXTag.SaveTags(music.Tags, music.MusicID);
			BizLyric.Update(
				music.MusicID, 
				m => new Lyric()
				{
					LyricWords = music.LyricWords
				}
			);
			db.Update(
				music.MusicID,
				g => new Music
				{
					Description = music.Description,
					Name = music.Name,
					Stars = music.Stars,
					MusicUrl = music.MusicUrl,
				}
			);
		}

		public Music[] FindByMusicNameAndStarName(string musicName, string starName)
		{
			return db.ListBy(music => music.Name.Contains(musicName) && music.Stars.Contains(starName));
		}
	}
}
